package com.yt.base.controller.base;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.yt.base.controller.core.BaseController;
import com.yt.base.model.*;
import com.yt.base.service.*;
import com.yt.base.util.Constants;
import com.google.common.base.Strings;
import com.google.common.collect.Maps;
import com.yt.core.MsgBean;
import com.yt.core.dao.PagingBean;
import com.yt.core.dao.filter.DynamicSQLFilterImpl;
import com.yt.core.dao.filter.QueryFilter;
import com.yt.util.MD5Util;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.Conventions;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.google.common.base.Splitter;
import com.google.common.collect.Lists;

@Controller
@RequestMapping("/base/user")
public class UserAclController extends BaseController {

	private final Logger logger = LoggerFactory.getLogger(getClass());

	@Autowired
	private AclUserService userService;
	@Autowired
	private AclCategoryService catService;
	@Autowired
	private AclPrivilegeService privService;
	@Autowired
	private AclOperationService opService;
	@Autowired
	private AclUserOperationService userOpService;
	@Autowired
	private AclGroupOperationService groupOpService;
	@Autowired
	private AclGroupService groupService;

	@RequestMapping("/toPermission")
	public ModelAndView toPermission(@RequestParam("uid") Long uid, HttpServletRequest request) {

		ModelAndView mav = new ModelAndView("base/user/UserPermission");

		AclUser user = userService.get(uid);
		mav.addObject("editingUser", user);

		List<AclCategory> categoryList = catService.findAll();
		List<AclPrivilege> privilegeList = privService.findAll();
		List<AclOperation> operationList = opService.findAll();

		mav.addObject("categoryList", categoryList);
		mav.addObject("privilegeList", privilegeList);
		mav.addObject("operationList", operationList);

		List<String> keyList = Lists.newArrayList();
		QueryFilter filter = new DynamicSQLFilterImpl();
		filter.addFilter("Q_userId_L_EQ", uid + "");
		filter.setPagingBean(new PagingBean(0, 1000));
		List<AclUserOperation> userOpList = userOpService.find(filter);

		if (userOpList != null && !userOpList.isEmpty()) {
			for (AclUserOperation op : userOpList) {
				StringBuilder sb = new StringBuilder().append(op.getCategoryId()).append("_").append(op.getPrivilegeId()).append("_").append(op.getOperationId());
				keyList.add(sb.toString());
			}
		} else {
			// 如用户权限表无记录，则去对应的Group权限
			List<AclGroupOperation> groupOpList = groupOpService.findByGroup(user.getGroupId());
			for (AclGroupOperation op : groupOpList) {
				StringBuilder sb = new StringBuilder().append(op.getCategoryId()).append("_").append(op.getPrivilegeId()).append("_").append(op.getOperationId());
				keyList.add(sb.toString());
			}
		}

		mav.addObject("keyList", keyList);
		return mav;
	}

	@RequestMapping("/saveAcl")
	public
	@ResponseBody
	Object saveAcl(@RequestParam("aclist") String aclist, @RequestParam("uid") Long uid) {
		logger.debug("更新用户[{}]权限", uid);

		MsgBean msg = new MsgBean();

		AclUser user = userService.get(uid);
		if (user == null) {
			msg.setFailure("1", "用户不存在");
		} else if (StringUtils.isEmpty(aclist.trim())) {
			msg.setFailure("1", "权限集合不可为空");
		} else {
			List<String> aclList = Splitter.on(',').trimResults().splitToList(aclist);
			userOpService.modify(user, aclList);
		}
		return msg.returnMsg();
	}

	@RequestMapping("/search")
	public
	@ResponseBody
	Object search(@RequestParam("name") String name) {
		logger.debug("查询用户名：" + name);

		MsgBean msg = new MsgBean();
		if (Strings.isNullOrEmpty(name)) {
			msg.setFailure("查询条件不可为空!");
		} else {
			List<AclUser> userList = userService.searchByName(name);
			msg.put("data", userList);
		}
		return msg.returnMsg();
	}

	@RequestMapping("/list")
	public ModelAndView list(@RequestParam(value = "name", required = false) String name, @RequestParam(value = "nick", required = false) String nick, @RequestParam(value = "start", required = false) String start, @RequestParam(value = "limit", required = false) String limit, HttpServletRequest request) {
		ModelAndView mav = new ModelAndView("base/user/UserList");

		PagingBean page = new PagingBean();
		int currentPage = 0;
		int pageSize = 25;
		if (StringUtils.isNotEmpty(limit) && StringUtils.isNumeric(limit)) {
			pageSize = Integer.parseInt(limit);
		}
		if (StringUtils.isNotEmpty(start) && StringUtils.isNumeric(start)) {
			currentPage = (Integer.parseInt(start) - 1) * pageSize;
		}

		page.setPageSize(pageSize);
		page.setStart(currentPage);

		QueryFilter filter = new DynamicSQLFilterImpl();
		filter.setPagingBean(page);
		filter.setSortField("id", true);
		if (StringUtils.isNotEmpty(name)) {
			filter.addFilter("Q_name_S_LK", name.trim());
			mav.addObject("name", name);
		}
		if (StringUtils.isNotEmpty(nick)) {
			filter.addFilter("Q_nick_S_LK", nick.trim());
			mav.addObject("nick", nick);
		}
		List<AclUser> userList = userService.find(filter);
		int userCount = userService.count(filter);
		mav.addObject("userList", userList);

		List<AclGroup> groupList = groupService.findAll();
		Map<Long, String> groupNameMap = Maps.newHashMap();
		for (AclGroup group : groupList) {
			groupNameMap.put(group.getId(), group.getName());
		}
		mav.addObject("start", start);
		mav.addObject("limit", limit);
		mav.addObject("total", userCount);
		mav.addObject("groupNameMap", groupNameMap);
		return mav;
	}

	@RequestMapping(value = "/toAdd")
	public ModelAndView toAdd(@RequestParam(value = "id", required = false) Long id) {
		ModelAndView mav = new ModelAndView("base/user/UserAdd");
		if (id != null && id > 0) {
			AclUser user = userService.get(id);
			if (user != null) {
				mav.addObject("editingUser", user);
			}
		}
		mav.addObject("groupList", groupService.findAll());
		return mav;
	}

	/**
	 * 保存用户信息
	 *
	 * @param name
	 * @param nick
	 * @param password
	 * @param groupId
	 * @param uid
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/add")
	public
	@ResponseBody
	Object add(@RequestParam("name") String name, @RequestParam(value = "nick") String nick, @RequestParam("password") String password, @RequestParam(value = "groupId") Long groupId,
			   @RequestParam(value = "uid", required = false) Long uid, HttpServletRequest request) {
		MsgBean msg = new MsgBean();
		try {
			logger.debug("保存用户：" + name);
			if (Strings.isNullOrEmpty(name.trim())) {
				msg.setFailure(1, ("用户名不可为空"));
				return msg.returnMsg();
			}

			AclUser dbUser = userService.findByName(name);
			if (dbUser != null && !dbUser.getId().equals(uid)) {
				msg.setFailure(1, ("用户名已被占用"));
				return msg.returnMsg();
			}
			if (uid == null) {
				AclUser user = new AclUser(name, nick, MD5Util.MD5(password), groupId);
				userService.insert(user);
			} else {
				AclUser user = userService.get(uid);
				user.setName(name);
				user.setNick(nick);
				if (!user.getPassword().equals(MD5Util.MD5(password))) {
					user.setPassword(MD5Util.MD5(password));
				}
				// 变更组，则清除用户原有权限
				if (user.getGroupId().longValue() != groupId) {
					userOpService.removeUserOp(uid);
				}
				user.setGroupId(groupId);
				userService.update(user);
			}
		} catch (Exception e) {
			logger.error("添加或修改用户出错：{}", e.getMessage(), e);
		}
		return msg.returnMsg();
	}

	@RequestMapping("/toModify")
	public ModelAndView toModify(@RequestParam("uid") Long uid, HttpServletRequest request) {
		ModelAndView mav = new ModelAndView("base/user/UserAdd");
		mav.addObject("editingUser", userService.get(uid));
		mav.addObject("groupList", groupService.findAll());
		return mav;
	}

	@RequestMapping("/modify")
	public
	@ResponseBody
	Object modify(AclUser editingUser) {

		MsgBean msg = new MsgBean();
		if (editingUser != null && editingUser.getId() != null && userService.get(editingUser.getId()) != null) {
			userService.update(editingUser);
		} else {
			msg.setFailure("1", "提交信user息有误");
		}
		return msg.returnMsg();
	}

	@RequestMapping("/del")
	public
	@ResponseBody
	Object del(@RequestParam("uid") Long uid) {
		logger.info("删除用户：" + uid);

		MsgBean msg = new MsgBean();
		userService.remove(uid);
		userOpService.removeUserOp(uid);
		return msg.returnMsg();
	}

	public static void main(String[] args) {
		Map<String, String> attributeValue = Maps.newHashMap();

		String str = Conventions.getVariableName(attributeValue);
		System.out.println(str);
	}

	/**
	 * to updatePassword
	 *
	 * @param request
	 * @return
	 */
	@RequestMapping("/toUpdatePass")
	public
	@ResponseBody
	ModelAndView toUpdatePasss(@RequestParam(value = "flag", required = false) String flag, HttpServletRequest request) {
		ModelAndView mav = new ModelAndView("base/user/updatePass");
		mav.addObject("user", request.getSession().getAttribute(Constants.LOGINUSER));
//		if (StringUtils.isNotEmpty(flag) && flag.equals("1")) {
//			mav.addObject("msg", "您的密码过于简单，请重新设置密码！");
//		}
		return mav;
	}

	/**
	 * 修改密码
	 *
	 * @param request
	 * @return
	 */
	@RequestMapping("/updatePass")
	public
	@ResponseBody
	Object updatePass(@RequestParam(value = "id") long id, @RequestParam(value = "oldPass") String oldPass, @RequestParam(value = "password") String password,
					  HttpServletRequest request) {
		MsgBean msg = new MsgBean();
		if (id > 0 && StringUtils.isNotEmpty(password)) {
			AclUser user = userService.get(id);
			if (user != null && MD5Util.MD5(oldPass).equals(user.getPassword())) {
				user.setPassword(MD5Util.MD5(password));
				userService.update(user);
				request.getSession().removeAttribute(Constants.USER_OP_KEY);
				request.getSession().removeAttribute(Constants.USER_MENU_KEY);
				request.getSession().removeAttribute(Constants.LOGINUSER);
			} else {
				msg.setFailure(1, "密码输入错误，请重试！");
			}
		} else {
			msg.setFailure(1, "旧密码不能为空！");
			return msg.returnMsg();
		}
		return msg.returnMsg();
	}
}
